#ifndef CHATSERVER_H
#define CHATSERVER_H

#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/epoll.h>
#include <map>
#include <vector>
#include <cstdlib>
#include <unistd.h>
#include <fcntl.h>
#include <cstring>
#include <json/json.h>

#define MAX_EPOLL_EVENT_NUM 1024
#define INVALID_FD -1
#define MAX_LISTEN_FD_NUM 1024
#define LISTEN_PORT 9000
#define MAX_RECV_BUF 65536

class ChatServer {
public :
    static ChatServer& getChatServerInstance() {
        static ChatServer chat_server;
        return chat_server;
    }
    int initSocket();
    int addFd(int fd, int flag);
    int deleteFd(int fd, int flag);
    int setSocket(int fd, int flag); 
    ~ChatServer();
    int run();
    //multicast
    int addIPtoMulti(std::string ip, std::string source_ip);
    int delIPfromMulti(std::string ip, std::string source_ip);
    int sendMsgtoMulti(std::string multi_ip_addr, std::string source_ip, std::string msg);
private :
    ChatServer();
    ChatServer(const ChatServer &);
    ChatServer& operator=(const ChatServer &);
public :
    int epoll_fd_;
    int server_socket_;
    int server_port_;
    std::map<std::string, int> client_ip2socket_;
    std::map<int, std::string> socket2client_ip_;
    epoll_event epoll_ready_event_[MAX_EPOLL_EVENT_NUM];
    std::map<std::string, std::vector<std::string> > dest_ip2message_;
    char read_buf_[MAX_RECV_BUF];
    //multicast
    std::map<std::string, std::vector<std::string> > multiaddr2ips_;
};

#endif
